package com.crysta1.aitrans;

import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PttDetailActivity extends AppCompatActivity {
    private static final String TAG = "PttDetailActivity";

    private DatabaseHelper dbHelper;

    private RecyclerView rv;
    private TextView tvEmpty;
    private PttAdapter adapter;
    private ImageButton btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptt_detail);

        // Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar_ptt);
        if (toolbar != null) {
            toolbar.setTitle("潜力值变化明细");
            setSupportActionBar(toolbar);
        }

        dbHelper = new DatabaseHelper(this);

        rv = findViewById(R.id.rvPtt);
        tvEmpty = findViewById(R.id.tvEmptyPtt);
        btnBack = findViewById(R.id.btnBack);

        if (rv != null) {
            rv.setLayoutManager(new LinearLayoutManager(this));
            adapter = new PttAdapter(new ArrayList<>());
            rv.setAdapter(adapter);
        }

        if (btnBack != null) {
            btnBack.setOnClickListener(v -> finish());
        }

        loadPttHistory();
    }

    private void loadPttHistory() {
        Cursor c = null;
        try {
            c = dbHelper.getStarHistoryCursor();
            ArrayList<PttItem> list = new ArrayList<>();
            if (c != null) {
                while (c.moveToNext()) {
                    long historyId = c.getLong(0);
                    String action = c.isNull(1) ? "" : c.getString(1);
                    int oldStars = c.isNull(2) ? 0 : c.getInt(2);
                    int newStars = c.isNull(3) ? 0 : c.getInt(3);
                    int delta = c.isNull(4) ? 0 : c.getInt(4);
                    float potBefore = c.isNull(5) ? 0f : c.getFloat(5);
                    float potAfter = c.isNull(6) ? 0f : c.getFloat(6);
                    String reason = c.isNull(7) ? "" : c.getString(7);
                    long ts = c.isNull(8) ? 0L : c.getLong(8);

                    Long quizId = parseIdFromReason(reason);
                    QuizRecord quiz = null;
                    if (quizId != null) {
                        quiz = queryQuizById(quizId);
                    }
                    if (quiz == null && ts > 0) {
                        quiz = queryQuizByTimestamp(ts);
                    }

                    list.add(new PttItem(historyId, action, oldStars, newStars, delta,
                            potBefore, potAfter, reason, ts, quiz));
                }
            }

            if (adapter != null) adapter.setData(list);
            if (tvEmpty != null) tvEmpty.setVisibility(list.isEmpty() ? View.VISIBLE : View.GONE);

            Log.d(TAG, "loaded ptt history count=" + (adapter == null ? 0 : adapter.getItemCount()));
        } catch (Exception e) {
            Log.e(TAG, "loadPttHistory error", e);
        } finally {
            if (c != null) c.close();
        }
    }

    private Long parseIdFromReason(String reason) {
        if (TextUtils.isEmpty(reason)) return null;
        Pattern p = Pattern.compile("id=(\\d+)");
        Matcher m = p.matcher(reason);
        if (m.find()) {
            try {
                return Long.parseLong(m.group(1));
            } catch (Exception ignored) { }
        }
        return null;
    }

    private QuizRecord queryQuizById(long id) {
        Cursor c = null;
        try {
            c = dbHelper.getReadableDatabase().rawQuery(
                    "SELECT question, answer, ai_response, score, timestamp FROM " +
                            DatabaseHelper.TABLE_QUIZ_RECORDS + " WHERE id=? LIMIT 1",
                    new String[]{String.valueOf(id)});
            if (c != null && c.moveToFirst()) {
                String q = c.isNull(0) ? "" : c.getString(0);
                String a = c.isNull(1) ? "" : c.getString(1);
                String ai = c.isNull(2) ? "" : c.getString(2);
                float score = c.isNull(3) ? 0f : c.getFloat(3);
                long ts = c.isNull(4) ? 0L : c.getLong(4);
                return new QuizRecord(id, q, a, ai, score, ts);
            }
        } finally {
            if (c != null) c.close();
        }
        return null;
    }

    private QuizRecord queryQuizByTimestamp(long ts) {
        Cursor c = null;
        try {
            c = dbHelper.getReadableDatabase().rawQuery(
                    "SELECT id, question, answer, ai_response, score, timestamp FROM " +
                            DatabaseHelper.TABLE_QUIZ_RECORDS + " WHERE timestamp=? LIMIT 1",
                    new String[]{String.valueOf(ts)});
            if (c != null && c.moveToFirst()) {
                long id = c.isNull(0) ? 0L : c.getLong(0);
                String q = c.isNull(1) ? "" : c.getString(1);
                String a = c.isNull(2) ? "" : c.getString(2);
                String ai = c.isNull(3) ? "" : c.getString(3);
                float score = c.isNull(4) ? 0f : c.getFloat(4);
                long ts2 = c.isNull(5) ? 0L : c.getLong(5);
                return new QuizRecord(id, q, a, ai, score, ts2);
            }
        } finally {
            if (c != null) c.close();
        }
        return null;
    }

    private static class PttItem {
        long historyId;
        String action;
        int oldStars, newStars, delta;
        float potBefore, potAfter;
        String reason;
        long ts;
        QuizRecord quiz;
        PttItem(long historyId, String action, int oldStars, int newStars, int delta,
                float potBefore, float potAfter, String reason, long ts, QuizRecord quiz) {
            this.historyId = historyId;
            this.action = action;
            this.oldStars = oldStars;
            this.newStars = newStars;
            this.delta = delta;
            this.potBefore = potBefore;
            this.potAfter = potAfter;
            this.reason = reason;
            this.ts = ts;
            this.quiz = quiz;
        }
    }

    private static class QuizRecord {
        long id; String question; String answer; String aiResponse; float score; long ts;
        QuizRecord(long id, String question, String answer, String aiResponse, float score, long ts) {
            this.id = id; this.question = question; this.answer = answer; this.aiResponse = aiResponse;
            this.score = score; this.ts = ts;
        }
    }

    private class PttAdapter extends RecyclerView.Adapter<PttAdapter.VH> {
        private ArrayList<PttItem> data;
        private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        PttAdapter(ArrayList<PttItem> data) { this.data = data; }

        void setData(ArrayList<PttItem> newData) { this.data = newData; notifyDataSetChanged(); }

        @Override
        public VH onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            View v = getLayoutInflater().inflate(R.layout.item_ptt_history, parent, false);
            return new VH(v);
        }

        @Override
        public void onBindViewHolder(VH holder, int position) {
            PttItem it = data.get(position);
            String time = it.ts > 0 ? sdf.format(new Date(it.ts)) : "—";
            holder.tvAction.setText(it.action + "  " + it.oldStars + "→" + it.newStars + " (Δ" + it.delta + ")");
            holder.tvPot.setText(String.format(Locale.getDefault(), "潜力: %.2f → %.2f", it.potBefore, it.potAfter));
            holder.tvTime.setText(time);

            if (it.quiz != null) {
                holder.tvQuestion.setText(it.quiz.question);
                holder.tvAnswer.setText("答案: " + it.quiz.answer);
                holder.tvExplain.setText("解析/AI: " + it.quiz.aiResponse);
                holder.tvScore.setText("分数: " + String.format(Locale.getDefault(), "%.2f", it.quiz.score));
            } else {
                holder.tvQuestion.setText("（未找到对应题目）");
                holder.tvAnswer.setText("");
                holder.tvExplain.setText(it.reason != null ? it.reason : "");
                holder.tvScore.setText("");
            }
        }

        @Override
        public int getItemCount() { return data == null ? 0 : data.size(); }

        class VH extends RecyclerView.ViewHolder {
            TextView tvAction, tvPot, tvTime, tvQuestion, tvAnswer, tvExplain, tvScore;
            VH(View itemView) {
                super(itemView);
                tvAction = itemView.findViewById(R.id.tvAction);
                tvPot = itemView.findViewById(R.id.tvPot);
                tvTime = itemView.findViewById(R.id.tvTime);
                tvQuestion = itemView.findViewById(R.id.tvQuestion);
                tvAnswer = itemView.findViewById(R.id.tvAnswer);
                tvExplain = itemView.findViewById(R.id.tvExplain);
                tvScore = itemView.findViewById(R.id.tvScore);
            }
        }
    }
}


